package server.unit;

import java.util.LinkedList;
import java.util.List;

public class BlockingQueue<T> {
    private final List<T> queue = new LinkedList<>();
    private volatile boolean canAddInQueue = true;

    public void setCanAddInQueue(boolean canAddInQueue) {
        this.canAddInQueue = canAddInQueue;
    }

    public boolean add(T element) {
        synchronized (queue) {
            if(!canAddInQueue) {
                return false;
            }
            queue.add(element);
            queue.notify();
            return true;
        }
    }

    public T remove() {
        synchronized (queue) {
            while (isEmpty()) {
                if(!canAddInQueue) {
                    return null;
                }
                try {
                    queue.wait();
                } catch (InterruptedException e) {}
            }
            return queue.remove(0);
        }
    }

    public boolean isEmpty() {
        synchronized (queue) {
            return queue.isEmpty();
        }
    }
}
